package com.fengcone.lucene.index.writer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.fengcone.lucene.analyzer.JiebaAnalyzer;

public class CaptionIndexWriter {
	private static final String FILE_PATH = "D:\\Lucene\\File";
	private static final String INDEX_PATH = "D:\\Lucene\\Index";

	public static void main(String[] args) throws IOException {
		File file = new File(FILE_PATH);
		JiebaAnalyzer analyzer = new JiebaAnalyzer();
		Directory index = FSDirectory.open(new File(INDEX_PATH).toPath());
		IndexWriterConfig config = new IndexWriterConfig(analyzer);

		IndexWriter writer = new IndexWriter(index, config);

		File[] files = file.listFiles();
		for (File file2 : files) {
			StringBuilder doc = new StringBuilder();
			BufferedReader reader = new BufferedReader(new FileReader(file2));
			String line = "";
			while ((line = reader.readLine()) != null && doc.length() < 2000) {
				doc.append(line);
			}
			Document document = new Document();
			document.add(new StringField("caption", doc.toString(), Store.YES));
			writer.addDocument(document);
			writer.commit();
			reader.close();
		}
		writer.close();
	}
}
